<template>
  <div class="app-container">
    <!--按钮-->
    <el-row>
      <el-button type="danger" size="medium" @click="deleteByIds">- 批量删除</el-button>
      <el-button type="primary" size="medium" @click="action = '新增';dialogVisible = true; admin = { header: ''};">+ 新增管理员
      </el-button>
    </el-row>

    <!--添加数据对话框表单-->
    <el-dialog :title="action" :visible.sync="dialogVisible" :before-close="reset" width="30%">
      <el-form ref="adminForm" :model="admin" :rules="adminRules" label-width="80px" size="mini">
        <el-form-item label="用户名" prop="username">
          <el-input
            ref="username"
            v-model="admin.username"
            placeholder="请输入用户名"
            name="username"
            type="text"
            tabindex="1"
            auto-complete="on"
          />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            ref="password"
            v-model="admin.password"
            type="password"
            name="password"
            placeholder="不修改请留空"
            @keyup.enter.native="add"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select v-model="admin.state" placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in stateList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :data="{ 'type': 'header' }"
            :headers="token"
            name="image"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="admin.header" :src="newHeader" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click.native.prevent="add">提交</el-button>
          <el-button @click="cancel()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <br>
    <!--表格-->
    <template>
      <el-table :data="tableData" style="width: 100%" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="username" label="姓名" align="center" />
        <el-table-column prop="header" label="头像" align="center">
          <template slot-scope="{ row }">
            <el-image style="width: auto; height: 40px; border: none; cursor: pointer" :src="row.header" />
          </template>
        </el-table-column>

        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <span style="margin-right: 10px">
              {{ scope.row.state == '1' ? '启用' : '禁用' }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建时间">
          <template slot-scope="scope">
            {{ scope.row.createTime ? scope.row.createTime.replace('T', ' ') : '' }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="最后操作时间">
          <template slot-scope="scope">
            {{ scope.row.updateTime ? scope.row.updateTime.replace('T', ' ') : '' }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="update(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteById(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="5"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { page, add, update, deleteById, selectById } from '@/api/admin.js'
import { getToken } from '@/utils/auth'
import { validUsername } from '@/utils/validate'

export default {
  data() {
    // 用户名校验规则
    const validateUsername = (rule, value, callback) => {
      if (!value || !validUsername(value)) {
        callback(new Error('请输入正确的用户名'))
      } else {
        callback()
      }
    }
    // 用户名校验规则
    const validatePassword = (rule, value, callback) => {
      if (!(this.action === '编辑' && !value) && (!value || value.length < 6)) {
        callback(new Error('密码长度至少为6位'))
      } else {
        callback()
      }
    }

    return {
      admin: {
        username: '',
        password: '',
        header: ''
      },
      adminRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 品牌模型数据
      searchAdmin: {
        name: '',
        state: ''
      },

      stateList: envConfig.adminSetting.stateList,

      beginTime: '',
      endTime: '',
      entrydate: '',

      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      token: { token: getToken() },
      action: '新增',
      uploadList: [],
      newHeader: ''
    }
  },

  watch: {
    entrydate(val) {
      if (val && val.length >= 2) {
        this.beginTime = val[0]
        this.endTime = val[1]
      } else {
        this.beginTime = ''
        this.endTime = ''
      }
    }
  },

  mounted() {
    this.page() // 当页面加载完成后，发送异步请求，获取数据
  },

  methods: {
    // 查询分页数据
    page() {
      page(
        this.searchAdmin.name,
        this.searchAdmin.state,
        this.beginTime,
        this.endTime,
        this.currentPage,
        this.pageSize
      ).then((res) => {
        this.totalCount = res.data.data.total
        this.tableData = res.data.data.rows
      })
    },

    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 查询方法
    onSubmit() {
      this.currentPage = 1
      this.page()
    },
    reset(done) {
      this.cancel()
      done()
    },
    clear() {
      this.searchAdmin = { name: '', state: '' }
      this.beginTime = '',
      this.endTime = ''
      this.entrydate = ''
      this.page()
    },
    // 添加数据
    add() {
      this.$refs.adminForm.validate(valid => {
        if (valid) {
          let operator
          if (this.admin.id) {
            // 修改
            operator = update(this.admin.id, this.admin, this.uploadList)
          } else {
            operator = add(this.admin)
          }

          operator.then((resp) => {
            if (resp.data.code == 1) {
              this.newHeader = ''
              this.uploadList = []
              this.dialogVisible = false
              this.page()
              this.$message({ message: '恭喜你，保存成功', type: 'success' })
              this.admin = { header: '' }
            } else {
              this.$message.error(resp.data.msg)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    update(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      this.action = '编辑'
      this.newHeader = ''
      // 2. 发送请求

      selectById(id).then((result) => {
        if (result.data.code === 1) {
          this.admin = result.data.data
          if (result.header) {
            this.newHeader = result.header
          }
        }
      })
    },
    // 取消修改
    cancel() {
      this.dialogVisible = false
      if (this.uploadList.length > 0) {
        update(this.admin.id, null, this.uploadList)
        this.uploadList = []
      }
    },

    // 删除员工信息
    deleteById(id) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 2. 发送AJAX请求
        deleteById(id).then((resp) => {
          if (resp.data.code == 1) {
            // 删除成功
            this.$message.success('恭喜你，删除成功')
            this.page()
          } else {
            this.$message.error(resp.data.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    // 批量删除员工信息
    deleteByIds() {
      // 弹出确认提示框
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确认按钮
        // 1. 创建id数组, 从 this.multipleSelection 获取即可
        for (let i = 0; i < this.multipleSelection.length; i++) {
          this.selectedIds[i] = this.multipleSelection[i].id
        }

        // 2. 发送AJAX请求
        deleteById(this.selectedIds).then((resp) => {
          if (resp.data.code == '1') {
            // 删除成功
            this.$message.success('恭喜你，删除成功')
            this.page()
          } else {
            this.$message.error(resp.data.msg)
          }
        })
      }).catch(() => {
        // 用户点击取消按钮
        this.$message.info('已取消删除')
      })
    },

    // 文件上传相关
    handleAvatarSuccess(res) {
      if (this.uploadList.length == 0 && this.admin.header !== '') {
        this.uploadList.push(this.admin.header)
      }
      this.uploadList.push(res.data)
      console.log(this.uploadList)
      this.admin.header = res.data
      this.newHeader = envConfig.headerUploadPath + res.data
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt500K = file.size / 1024 < 500
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG或PNG 格式!')
      }
      if (!isLt500K) {
        this.$message.error('上传头像图片大小不能超过 500KB!')
      }
      return isJPG && isLt500K
    },
    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val
      this.page()
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
